'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  const { userA, userB } = event;
  if (!userA || !userB) {
    return { code: 400, msg: '参数缺失' };
  }
  try {
    const res = await db.collection('chatMessages')
      .where({
        $and: [
          {
            $or: [
              { senderId: userA, receiverId: userB },
              { senderId: userB, receiverId: userA }
            ]
          },
          // 排除客服消息
          { receiverId: db.command.neq('admin') },
          { senderId: db.command.neq('admin') }
        ]
      })
      .orderBy('createTime', 'asc')
      .get();
    return { code: 200, data: res.data };
  } catch (e) {
    return { code: 500, msg: '数据库查询失败', error: e.message };
  }
};